package com.yuzi.project.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuzi.common.entity.InterfaceInfo;
import com.yuzi.project.common.ErrorCode;
import com.yuzi.project.exception.BusinessException;
import com.yuzi.project.exception.ThrowUtils;
import com.yuzi.project.mapper.InterfaceInfoMapper;
import com.yuzi.project.service.InterfaceInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;


/**
 * @author 29015
 * @description 针对表【interface_info(接口信息)】的数据库操作Service实现
 * @createDate 2024-03-13 19:39:04
 */
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
        implements InterfaceInfoService {
    @Override
    public void validInterface(InterfaceInfo interfaceInfo, boolean add) {
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String name = interfaceInfo.getName();
        String description = interfaceInfo.getDescription();
        String url = interfaceInfo.getUrl();
        String requestHeader = interfaceInfo.getRequestHeader();
        String responseHeader = interfaceInfo.getResponseHeader();
        String method = interfaceInfo.getMethod();
        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(name, description, url, method, requestHeader, responseHeader), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(name) && name.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "名称过长");
        }
        if (StringUtils.isNotBlank(description) && description.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "说明过长");
        }
        if (!StringUtils.isAnyEmpty(requestHeader, responseHeader) && requestHeader.length() > 360 && responseHeader.length() > 360) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求头，响应头过长");
        }
        if(StringUtils.isNotBlank(method) && method.length() > 25){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求方法过长");
        }
        if (StringUtils.isNotBlank(url) && url.length() > 255) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口地址过长");
        }
        if (StringUtils.isNotBlank(url) && !url.startsWith("http")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口地址必须以http开头");
        }
        if (StringUtils.isNotBlank(url) && !url.endsWith("/")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口地址必须以/结尾");
        }
    }
}




